package com.lepu.app.main.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragment;
import com.core.lib.utils.OnZoomImageClickCallBack;
import com.core.lib.utils.PopUtil;
import com.core.lib.utils.main.ImageUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.photo.BitmapUtil;
import com.core.lib.utils.photo.UniversalImageLoadTool;
import com.core.lib.widget.AnimationImageView;
import com.lepu.pasm.R;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class AppImageFragment extends BaseFragment{

	private View 	mMainView 			= null;
	private boolean mInitDataSuccess 	= false;//是否加载完数据
	private Bundle 	mData;
	private Bitmap 	mBitmap;
	private String 	mImageName;
	@SuppressLint("InflateParams")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mMainView = LayoutInflater.from(getActivity()).inflate(
				R.layout.app_image_fragment,null,
				false);
		init();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		ViewGroup p = (ViewGroup) mMainView.getParent();
		if (p != null) {
			p.removeAllViewsInLayout();
		}
		return mMainView;
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();

		mInitDataSuccess = false;
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);

		if (isVisibleToUser) {
			if (!mInitDataSuccess) {
				// 第一次进入页面获取数据
				mInitDataSuccess = true;
			}
		}
	}
	
	/*
	 * 初始化ui控件，不要初始化数据！！！！
	 * 
	 * 初始化控件，需要用mMainView.findViewById
	 * 不能使用findViewById，否则程序会闪退的
	 */
	private void init()
	{
		mData = getArguments();
		if(mData != null && mData.size() > 0)
		{
			final AnimationImageView imageView = createImageView();
			boolean isNet = mData.getBoolean("is_net");
			if(isNet)
			{
				String url = mData.getString("url");

				String imageUrl = "";
				if (url.startsWith("http")) {
					imageUrl = Setting.getImageUrl(url);
				} else {
					imageUrl = ImageUtilBase.getFileImageUrl(url);
				}

				LogUtilBase.LogD(null, "image_url=" + imageUrl);
				mImageName = getImageName(imageUrl);
				LogUtilBase.LogD(null, "mImageName=" + mImageName);

//				UniversalImageLoadTool.disPlayOrign(imageUrl, imageView,
//						R.drawable.default_icon_small);
				UniversalImageLoadTool.getImageLoader().loadImage(imageUrl, new ImageLoadingListener() {
					@Override
					public void onLoadingStarted(String s, View view) {
						 imageView.setImageDrawable(getResources().getDrawable(R.drawable.default_icon_small));
					}

					@Override
					public void onLoadingFailed(String s, View view, FailReason failReason) {
						imageView.setImageDrawable(getResources().getDrawable(R.drawable.default_icon_small));

					}

					@Override
					public void onLoadingComplete(String s, View view, Bitmap bitmap) {
						imageView.setImageBitmap(bitmap);
						mBitmap = bitmap;
					}

					@Override
					public void onLoadingCancelled(String s, View view) {
						imageView.setImageDrawable(getResources().getDrawable(R.drawable.default_icon_small));

					}
				});
			}else{
				String filePath = mData.getString("filePath");
				mBitmap = ImageUtilBase.getBitmap(filePath,480,800);
				imageView.setImageBitmap(BitmapUtil.reviewPicRotate(mBitmap, filePath));

			}

			LinearLayout contentLayout = (LinearLayout) mMainView.findViewById(R.id.contentLayout);
			contentLayout.addView(imageView);
		}
	}

	private String getImageName(String imageUrl) {
		int start 	= imageUrl.lastIndexOf("/") == -1 ? 0 					: imageUrl.lastIndexOf("/");
		int end		= imageUrl.lastIndexOf(".") == -1 ? imageUrl.length() 	: imageUrl.lastIndexOf(".");
		return imageUrl.substring(start == 0 ? 0 : start + 1, end);
	}

	@SuppressLint("InflateParams")
	private void showSaveImagePop() {
		View view = LayoutInflater.from(getActivity()).inflate(
				R.layout.chat_image_save_pop, null);
		RelativeLayout 	containerLayout 	= (RelativeLayout) 	view.findViewById(R.id.containerLayout);
		Button 			saveToLocalButton 	= (Button) 			view.findViewById(R.id.saveToLocalButton);
		Button 			cancelButton 		= (Button) 			view.findViewById(R.id.cancelButton);

		containerLayout		.setOnClickListener(mPopOnClickListener);
		saveToLocalButton	.setOnClickListener(mPopOnClickListener);
		cancelButton		.setOnClickListener(mPopOnClickListener);

		PopUtil.getInstance().showPopWindow(getActivity(), null, view, Gravity.BOTTOM,
				null, false);
	}

	private void dismissAddPop() {

		PopUtil.getInstance().dismissPopWindow();
	}

	View.OnClickListener mPopOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			int rid = v.getId();
			switch (rid) {
				case R.id.saveToLocalButton: {
					if (mBitmap != null) {
						saveImageToGallery(getActivity(), mBitmap);
					}
					break;
				}
				case R.id.cancelButton:
					break;
				case R.id.containerLayout:
					break;
				default:
					break;
			}
			dismissAddPop();
		}
	};

	public void saveImageToGallery(Context context, Bitmap bmp) {
//		http://stormzhang.com/android/2014/07/24/android-save-image-to-gallery/
		// 首先保存图片
		File appDir = new File(SdLocal.getLepuRootPathSD(context));
		if (!appDir.exists()) {
			appDir.mkdir();
		}
//		String fileName = System.currentTimeMillis() + ".jpg";
		String fileName = mImageName + ".jpg";
		File file = new File(appDir, fileName);
		if (file.exists()) {
			UIHelper.showToast(getActivity(), "图片已保存");

			return;
		}
		try {
			FileOutputStream fos = new FileOutputStream(file);
			bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 其次把文件插入到系统图库
		try {
			MediaStore.Images.Media.insertImage(context.getContentResolver(),
					file.getAbsolutePath(), fileName, null);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		// 最后通知图库更新
		context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));

		//**************第二种方式 华为荣耀6不能
//		MediaStore.Images.Media.insertImage(context.getContentResolver(),mBitmap,fileName,null);
		UIHelper.showToast(getActivity(), "保存成功");
		//**************
	}


	private AnimationImageView createImageView()
	{
		final AnimationImageView imageView = new AnimationImageView(
				getActivity());
		imageView.setLayoutParams(new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT));

		imageView.setAdjustViewBounds(true);
		imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
		imageView
				.setClickCallBack(new OnZoomImageClickCallBack() {

					@Override
					public void OnSingleTapConfirmed(PointF point) {
						getActivity().finish();
					}

					@Override
					public void OnLongClickResponse(PointF point) {
						showSaveImagePop();

					}

					@Override
					public void OnDoubleClickResponse(PointF point) {
						float magfactor = 1.6f;
						float float_epsilon = 1e-3f;
						float viewwidth = imageView.getWidth();
						float viewheight = imageView.getHeight();
						float imagewidth = imageView.getDrawable()
								.getBounds().width();
						float imageheight = imageView.getDrawable()
								.getBounds().height();

						Matrix matrix = new Matrix();
						matrix.set(imageView.getImageMatrix());
						float[] values = new float[9];
						matrix.getValues(values);

						float ratiox = viewwidth / imagewidth;
						float ratioy = viewheight / imageheight;
						float minratio = ratiox < ratioy ? ratiox
								: ratioy;
						float transx, transy;
						// 回原图
						if (values[0] > (minratio + float_epsilon)) {
							if (ratiox < ratioy) {
								transx = 0;
								transy = (viewheight - ratiox
										* imageheight) / 2;
							} else {
								transx = (viewwidth - ratioy
										* imagewidth) / 2;
								transy = 0;
							}
							values[0] = values[4] = minratio;
							values[2] = transx;
							values[5] = transy;
							matrix.setValues(values);
							imageView.EnableAnimation(
									imageView.getImageMatrix(),
									matrix, 200);
						} else {// 放大
							matrix.postScale(magfactor, magfactor,
									point.x, point.y);
							imageView.EnableAnimation(
									imageView.getImageMatrix(),
									matrix, 200);
						}
					}
				});
		return imageView;
	}
}
